package com.atguigu.daijia.driver.service.impl;

import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.driver.config.MinioProperties;
import com.atguigu.daijia.driver.service.FileService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class FileServiceImpl implements FileService {

    @Resource
    private MinioProperties minioProperties;

    /**
     * 上传文件到MinIO
     *
     * @param file 要上传的文件
     * @return 上传后的文件URL
     * @throws GuiguException 自定义异常，当上传过程中发生错误时抛出
     */
    @Override
    public String upload(MultipartFile file) {
        try {
            // 构建MinioClient实例，用于连接MinIO服务器
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioProperties.getEndpointUrl())
                    .credentials(minioProperties.getAccessKey(), minioProperties.getSecreKey())
                    .build();

            // 检查指定的存储桶是否已经存在
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());

            // 如果存储桶不存在，则创建它
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            } else {
                // 如果存储桶已经存在，则输出提示信息
                System.out.println("Bucket 'daijia' already exists.");
            }

            // 获取文件扩展名
            String extFileName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            // 生成新的文件名，包含日期和随机UUID，以避免文件名冲突
            String fileName = new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/" +
                    UUID.randomUUID().toString().replaceAll("-", "") + "." + extFileName;
            // 构建上传对象的参数
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .object(fileName)
                    .build();
            // 执行上传操作
            minioClient.putObject(putObjectArgs);

            // 返回文件的访问URL
            return minioProperties.getEndpointUrl() + "/" + minioProperties.getBucketName() + "/" + fileName;
        }catch (Exception e){
            // 如果发生异常，抛出自定义异常
            throw new GuiguException(ResultCodeEnum.FILE_ERROR);
        }
    }

}
